<template>
  <div
    :id="id"
    class="table-wrapper"
    ref="tableWrapper"
    :class="isAdd ? 'addTable' : 'detailTable'"
  >
    <div id="bkTable" ref="bkTable">
      <el-form :model="tableForm" :ref="refName">
        <el-table
          ref="elTable"
          :data="isAdd ? tableForm['tableData'] : tableData"
          stripe
          style="width: 100%"
          height="calc(100% - 60px)"
          :max-height="configSet.maxHeight || 'auto'"
          :header-cell-style="tableHeaderCellStyle"
          :cell-style="tableCellStyle"
          :span-method="objectSpanMethod"
          :row-key="configSet.rowKey || 'id'"
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
          @row-dblclick="rowdbClick"
        >
          <el-table-column
            v-if="configSet.showSelection"
            type="selection"
            width="50px"
            align="center"
            :reserve-selection="config.reserveSelection"
            :cell-style="{ padding: '0 0' }"
            :selectable="selectable"
          />
          <el-table-column
            v-if="configSet.showIndex"
            label="序号"
            type="index"
            width="55"
            align="center"
            :cell-style="{ padding: '0 0' }"
          />
          <el-table-column
            v-for="(item, index) in tableHeadConfig"
            :prop="item.prop"
            :label="item.label"
            :align="item.align || 'left'"
            :width="
              !item.btnList || item.fixPx ? countW(item.width) : item.width
            "
            :sortable="item.sortable"
            :sort-method="item.sortMethod"
            :key="index"
            :show-overflow-tooltip="
              item.showTooltip === undefined ? true : item.showTooltip
            "
            :cell-style="{ padding: '0 0' }"
          >
            <template slot-scope="scope">
              <div class="table-column" v-if="!item.btnList && isAdd">
                <el-form-item
                  :prop="'tableData.' + scope.$index + '.' + item.prop"
                  :rules="item.rules ? item.rules(scope) : []"
                >
                  <!-- 下拉框 -->
                  <el-select
                    v-model="scope.row[item.prop]"
                    v-if="item.type === 'select'"
                    :disabled="isDisabled || item.disabled"
                  >
                    <el-option
                      v-for="(ele, ind) in item.options"
                      :key="ind"
                      :label="
                        item.props && Object.keys(item.props).length
                          ? ele[item.props.label]
                          : ele.label
                      "
                      :value="
                        item.props && Object.keys(item.props).length
                          ? ele[item.props.value]
                          : ele.value
                      "
                    />
                  </el-select>
                  <!-- 时间框 -->
                  <el-date-picker
                    v-else-if="item.type === 'date'"
                    v-model="scope.row[item.prop]"
                    value-format="yyyy-MM-dd"
                    type="date"
                    :placeholder="item.placeholder"
                    :disabled="isDisabled || item.disabled"
                  />
                  <!-- 数字文本框 -->
                  <el-input
                    v-else-if="item.type === 'number'"
                    v-model="scope.row[item.prop]"
                    @keyup.native="numKeyUp($event, scope.$index, item)"
                    :max="item.max"
                    :min="item.min"
                    @blur="
                      item.handleBlur &&
                        item.handleBlur(scope.row, scope.$index, item.prop)
                    "
                    :disabled="isDisabled || item.disabled"
                  />

                  <!-- 文本框 -->
                  <el-input
                    v-else-if="item.type === 'input'"
                    v-model="scope.row[item.prop]"
                    :disabled="isDisabled || item.disabled"
                    @blur="
                      item.handleBlur &&
                        item.handleBlur(scope.row, scope.$index, item.prop)
                    "
                  />
                  <!-- slot -->
                  <slot
                    class="slot-item"
                    v-else-if="item.type === 'slot'"
                    :row="scope.row"
                    :prop="item"
                  ></slot>
                  <!-- nameSlot -->
                  <slot
                    class="slot-item"
                    v-else-if="item.type === 'nameSlot'"
                    :row="scope.row"
                    :prop="item"
                    :name="item.prop"
                    :index="index"
                  ></slot>
                  <!-- 文本 -->
                  <div v-else-if="item.type === 'text'">
                    <div>
                      {{
                        (item.formatter &&
                          item.formatter(scope.row[item.prop], scope.row)) ||
                        scope.row[item.prop]
                      }}
                    </div>
                  </div>
                </el-form-item>
              </div>
              <div class="table-column" v-if="!item.btnList && !isAdd">
                <div v-if="item.type === 'switch'">
                  <!-- 开关 -->
                  <el-switch
                    v-model="scope.row[item.prop]"
                    :active-color="item.activeColor || '#13ce66'"
                    :inactive-color="item.inactiveColor || '#ff4949'"
                    :active-text="item.activeText || ''"
                    :inactive-text="item.inactiveText || ''"
                    :active-value="item.activeValue"
                    :inactive-value="item.inactiveValue"
                    :disabled="isDisabled || item.disabled"
                    @change="
                      item.change
                        ? item.change(scope.row, scope.$index, item.prop)
                        : null
                    "
                  ></el-switch>
                </div>
                <div v-else-if="item.type === 'tooltip'">
                  <el-tooltip
                    popper-class="atooltip"
                    class="item"
                    effect="dark"
                    placement="top-start"
                    :disabled="
                      scope.row['tooltip'] == undefined ||
                      scope.row['tooltip'].length == 0
                    "
                  >
                    <div
                      slot="content"
                      v-html="
                        item.setContent
                          ? item.setContent(scope.row)
                          : scope.row[item.prop]
                      "
                    ></div>
                    <div
                      :class="{
                        special:
                          (item.flag
                            ? item.flag.includes(scope.row[item.prop])
                            : false) || false,
                      }"
                    >
                      {{
                        (item.formatter &&
                          item.formatter(scope.row[item.prop])) ||
                        scope.row[item.prop]
                      }}
                    </div>
                  </el-tooltip>
                </div>
                <div v-if="item.formatter">
                  {{
                    item.formatter &&
                    item.formatter(scope.row[item.prop], scope.row)
                  }}
                </div>
                <div v-else-if="item.render">
                  <div v-html="item.render(scope.row)"></div>
                </div>
                <div v-else-if="item.btnRender">
                  <List :config="item" :data="scope.row" :index="index" />
                </div>
                <div v-else-if="item.slot">
                  <slot :row="scope.row" :prop="item"></slot>
                </div>
                <div v-else-if="item.nameSlot">
                  <slot
                    :name="item.prop"
                    :row="scope.row"
                    :prop="item"
                    :index="scope.$index"
                  ></slot>
                </div>

                <div v-else>{{ scope.row[item.prop] }}</div>
              </div>
              <!-- 操作按钮 -->
              <div v-if="item.btnList" class="btn-wrapper">
                <div v-for="(ele, ind) in item.btnList" :key="ind">
                  <List
                    v-if="ele.isShow ? ele.isShow(scope.row) : true"
                    class="btn-box"
                    :config="ele"
                    :data="scope.row"
                    :index="scope.$index"
                  />
                </div>
              </div>
            </template>
            <div v-if="item.children && item.children.length">
              <el-table-column
                v-for="(ele, ind) in item.children"
                :key="ind"
                :prop="ele.prop"
                :label="ele.label"
                :width="ele.width"
                :sortable="ele.sortable"
                :sort-method="ele.sortMethod"
              >
              </el-table-column>
            </div>
          </el-table-column>
        </el-table>

        <div class="table-page" v-if="configSet.showPage">
          <div class="desc">
            <slot name="desc"></slot>
          </div>
          <div class="page">
            <el-pagination
              background
              @size-change="changeSize"
              @current-change="changePage"
              :page-sizes="pageSizes"
              :page-size="page.pageSize"
              :current-page="page.pageNum"
              layout="total, sizes, prev, pager, next"
              :total="total"
            />
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BkTable',
  components: {},
  props: {
    id: {
      type: String,
      default: "table-wrapper",
    },
    tableForm: {
      type: Object,
      default: () => {},
    },
    tableData: {
      type: Array, // 表格
      default: () => {},
    },
    tableHead: {
      type: Array, // 表格
      default: () => [],
    },
    config: {
      type: Object,
      default: () => {},
    },
    isAdd: {
      type: Boolean,
      default: false,
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
    refName: {
      type: String,
      default: "tableForm",
    },
    page: {
      type: Object,
      default: () => {
        return {
          pageSize: 10,
          pageNum: 1,
        };
      },
    },
    pageSizes: {
      type: Array,
      default: () => [10, 30, 50, 100],
    },
    total: {
      type: Number,
      default: 0,
    },
    tableHeaderCellStyle: {
      type: Object,
      default: function () {
        return {
          background: "rgb(243, 243, 245)",
          padding: "6px 0",
          color: "#333",
        };
      },
    },
    tableCellStyle: {
      type: Object,
      default: function () {
        return {
          padding: "6px 0",
          color: "#666",
        };
      },
    },
    defaultList: {
      type: Array,
      default: () => [],
    },
    selectable: {
      type: Function,
      default: () => {
        return true;
      },
    },
    objectSpanMethod: {
      type: Function,
      default: () => {
        return {
          rowspan: 1,
          colspan: 1,
        };
      },
    },
    load: {
      type: Function,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      tableH: 100,
      maxTableH: 100,
    };
  },
  created() {},
  mounted() {
    // this.$bus.on("handleClick", this.countHeight);
    this.countHeight();
  },
  destroyed() {
    // this.$bus.off("handleClick");
  },
  updated() {},
  computed: {
    configSet() {
      let obj = {
        showPage: true,
        showSelection: false,
        showIndex: true,
        reserveSelection: false,
        rowKey: "id",
      };
      return Object.assign(obj, this.config);
    },
    tableHeadConfig() {
      let temp = [];
      this.tableHead.forEach((el) => {
        if (!el.hidden) {
          temp.push(el);
        }
      });
      return Object.assign({}, temp);
    },
  },
  methods: {
    countW(px) {
      // if(!px) {
      let fontSize = document.getElementsByTagName("html")[0].style.fontSize;
      return `${(parseFloat(px) * parseFloat(fontSize)) / 100}px`;
      // } else {
      //   return ''
      // }
    },
    countHeight() {
      this.$nextTick(() => {
        let el = this.$refs.tableWrapper;
        if (el) {
          let parentNodesH = document.getElementById(el.id).parentNode
            .clientHeight;
          let nodes = document.getElementById(el.id);
          var sibNodes = this.siblings(nodes); //保存所有兄弟节点
          let exitH = 0;
          sibNodes.forEach((el) => {
            exitH += el.clientHeight;
          });
          el.style.height = parentNodesH - exitH + "px";
        }
      });
    },
    siblings(elm) {
      var a = []; //保存所有兄弟节点
      var p = elm && elm.parentNode ? elm.parentNode.children : []; //获取父级的所有子节点
      for (var i = 0; i < p.length; i++) {
        //循环
        if (p[i].nodeType == 1 && p[i] != elm) {
          //如果该节点是元素节点与不是这个节点本身
          a.push(p[i]); // 添加到兄弟节点里
        }
      }
      return a;
    },
    changeSize(val) {
      if (this.total < val) {
        this.page.pageNum = 1;
      }
      this.page.pageSize = val;
      this.$emit("getList", { ...this.page });
    },
    changePage(val) {
      this.page.pageNum = val;
      this.$emit("getList", { ...this.page });
    },
    handleSelectionChange(val) {
      this.$emit("handleSelectionChange", val);
    },
    toggleSelection(rows) {
      let that = this;
      if (rows.length) {
        for (let i = 0; i < rows.length; i++) {
          that.$refs.elTable.toggleRowSelection(rows[i], true);
        }
      } else {
        this.$refs.elTable.clearSelection();
      }
    },
    rowdbClick(row, column, event) {
      this.$emit("rowdbClick", row, column, event);
    },
    numKeyUp(e, index, item) {
      if (item.dataType == "float") {
        if (e.target.value.indexOf(".") > -1) {
          e.target.value = e.target.value.match(/\d+\.?\d{0,2}/, "");
        }
      } else {
        e.target.value = e.target.value.replace(/[^\d]/g, "");
      }
      this.$set(this.tableForm.tableData[index], item.prop, e.target.value);
    },
    tableValid() {
      let that = this;
      return new Promise((resolve, reject) => {
        that.$refs[that.refName].validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    renderHeader(h, { column, $index }) {
      if (column.label.split("/")[1]) {
        return h("div", [
          h(
            "div",
            { class: "table-head", style: { width: "100%" } },
            column.label.split("/")[0]
          ),
          h("div", { class: "table-heag", style: { width: "100%" } }, ""),
          h(
            "div",
            { class: "table-head", style: { width: "100%" } },
            column.label.split("/")[1]
          ),
        ]);
      } else {
        return column.label.split("/")[0];
      }
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
#bkTable {
  // background-color: #fff;
  // padding: 20px;
  box-sizing: border-box;
  height: 100%;
  // box-shadow: 0px 0px 21px 0px rgba(211, 219, 232, 0.5);
  border-radius: 4px;

  ::v-deep .el-form {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    // .bk-table-box{
    //   flex: 1;
    // }
    .el-form-item {
      .el-form-item__content {
        overflow: hidden;
      }
    }

    .el-table {
      // height: 100%;
      flex: 1;

      &:before {
        content: "";
        height: 0;
      }

      .cell {
        height: 32px;
        line-height: 32px;

        .table-column {
          display: inline-block;
        }
      }
    }

    .table-page {
      border-top: 1px solid #eff0f5;
      padding: 0.1rem 0;
      position: relative;

      .desc {
        position: absolute;
        top: 16px;
        left: inherit;
        background-color: #fff;
        height: auto;
      }

      .page {
        text-align: right;

        .el-pager {
          li {
            &:not(.disabled) {
              &.active {
                background-color: #165dff;
              }
            }
          }
        }
      }
    }
  }

  .desc {
    background-color: #fff;
    height: auto;
  }

  .btn-wrapper {
    text-align: left;

    div {
      display: inline-block;
    }
  }

  .btn-box {
    display: inline-block;
    margin-right: 8px;
    margin-left: 8px;

    ::v-deep .el-button {
      height: 32px;
      line-height: 32px;
      padding: 0 15px;
    }
  }
}

.pagination {
  background-color: #fff;
  margin-top: 0;
  height: auto;
  padding-bottom: 10px;
  padding-right: 20px;
}

.addTable {
  #bkTable {
    ::v-deep .el-form {
      ::v-deep .cell {
        height: 42px;
        line-height: 42px;

        ::v-deep .el-input {
          width: 100%;

          ::v-deep .el-input__inner {
            height: 32px;
            line-height: 32px;
          }
        }
      }

      .has-gutter {
        .cell {
          height: 35px;
          line-height: 35px;
        }
      }
    }
  }

  .special {
    color: #165dff;
  }
}
</style>
